#!/usr/bin/perl

use strict;
use FindBin qw($Bin);
use Getopt::Long;
require "$Bin/misc/devlib.pl";

my @blobref_arg;
my $opt_xterm;
my $opt_verbose;

GetOptions(
    "xterm" => \$opt_xterm,
    "verbose" => \$opt_verbose,
) or usage();

if (@ARGV) {
    my $blobref = shift;
    unless ($blobref && $blobref =~ /^\w+-[0-9a-f]{10,}$/) {
        die "Usage: dev-cammount [<blobref>]\n";
    }
    push @blobref_arg, $blobref;
}

my $cammount = build_bin("./cmd/cammount");
unless (-x $cammount) { die "Failed to find $cammount" }

my $dir = "/tmp/cammount-dir";

try_unmount();

mkdir $dir, 0700 unless -d $dir;

print "Mounting on $dir ...\n";

# Respected by camli/osutil:
$ENV{"CAMLI_CONFIG_DIR"} = "$Bin/config/dev-client-dir";

# Respected by env expansions in config/dev-client-dir/client-config.json
$ENV{"CAMLI_SECRET_RING"} = "$Bin/pkg/jsonsign/testdata/test-secring.gpg";
$ENV{"CAMLI_KEYID"} = "26F5ABDA";
$ENV{"CAMLI_DEV_KEYBLOBS"} = "$Bin/config/dev-client-dir/keyblobs";
$ENV{"CAMLI_AUTH"} = "userpass:camlistore:pass3179";

print "############################################################################\n## Press 'q' <enter> to shut down.\n##\n";

exec("$cammount",
     "--xterm=" . ($opt_xterm ? "true" : "false"),
     "--debug=" . ($opt_verbose ? "true" : "false"),
     "--server=http://localhost:3179/bs", $dir, @blobref_arg)
    and warn "cammount failure: $!\n";
warn "Failed to unmount\n" unless try_unmount();

sub try_unmount {
    if ($^O eq "darwin") {
        unless (`df -n` =~ /\Q$dir\E/) {
            return 1;
        }
        print "Running: diskutil unmount force $dir ...\n";
        return system("diskutil", "umount", "force", $dir) == 0;
    }
    if ($^O eq "linux" && system("fusermount", "-u", $dir) == 0) {
        return 1;
    }
    return 1 if system("umount", $dir) == 0;
    return 1 if system("umount", "-f", $dir) == 0;
    return 0;
}
